package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysMember;
import com.ruoyi.system.domain.dto.SmsRegisterDto;
import com.ruoyi.system.mapper.SysMemberMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SmsService;
import com.ruoyi.system.service.impl.SysMemberServiceImpl;
import com.ruoyi.system.util.SmsCodeUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@Anonymous
@RequestMapping("/api/sms")
public class SmsRegisterController extends BaseController {

    //    @Autowired
//    private AliyunSmsService smsService;
    @Autowired
    @Lazy
    private SysLoginService loginService;
    @Autowired
    private SmsCodeUtil smsCodeUtil;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SmsService smsService;
    //    @Autowired
//    private SmsUtil smsUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysMemberServiceImpl sysMemberServiceImpl;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserMapper sysUserMapper;
//    @Autowired
//    private TokenService tokenService;

    /**
     * 发送注册验证码
     */
    @GetMapping("/sendRegisterCode/{phoneNumber}")
    public AjaxResult sendRegisterCode(@PathVariable String phoneNumber) {

        if (ObjectUtils.isNotEmpty(redisCache.getCacheObject("sms_code:" + phoneNumber))) {
            return AjaxResult.error("请在一分钟后重试～");
        }
//
//        if (sysMemberServiceImpl.checkPhoneByPhone(phoneNumber)) {
//            return AjaxResult.error("该手机号已注册！");
//        }

        // 生成并发送验证码
        String code = smsCodeUtil.generateCode();
        // 假设短信模板需要一个验证码参数
        String templateParam = "{\"code\":\"" + code + "\"}";

        boolean isSuccess = smsService.sendSms(phoneNumber, templateParam);
        if (isSuccess) {
            smsCodeUtil.saveCode(phoneNumber, code);
            return AjaxResult.success("短信发送成功");
        } else {
            return AjaxResult.error("短信发送失败");
        }
    }

    /**
     * 手机号注册接口
     * 用户通过手机号进行注册，需要验证验证码是否正确，若验证码正确且手机号未注册则进行注册操作，否则返回相应错误信息。
     *
     * @param registerDto 注册信息，包括手机号、验证码和密码
     * @return AjaxResult 注册结果，包含是否成功及相应提示信息
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SmsRegisterDto registerDto) {
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.smsLogin(registerDto);
        SysMember sysMember = sysMemberMapper.selectSysMemberByPhone(registerDto.getPhoneNumber());
        ajax.put(Constants.TOKEN, token);
        ajax.put("memberId",null != sysMember?sysMember.getId():null);
        return ajax;
    }

    /**
     * 获取会员信息详细信息
     */
    @ApiOperation("获取会员信息详细信息")
    // @PreAuthorize("@ss.hasPermi('system:member:query')")
    @GetMapping("/openIdInfo/{openId}")
    public Map<String, Object> openIdInfo(@PathVariable("openId") String openId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        if (ObjectUtils.isNotEmpty(openId)) {
            SysUser user = new SysUser();
            user.setOpenId(openId);
            List<SysMember> res = new ArrayList<>();
            List<SysUser> sysUsers = sysUserMapper.selectUserList(user);
            if (ObjectUtils.isNotEmpty(sysUsers)){
//                for (SysUser sysUser : sysUsers) {
//                    res.add(sysMemberMapper.selectSysMemberByPhone(sysUser.getPhonenumber()));
//                }
                LoginUser loginUser = new LoginUser();
                loginUser.setUser(sysUsers.get(0));
                map.put("token", tokenService.createToken(loginUser));
                SysMember param = new SysMember();
                param.setOpenId(openId);
                List<SysMember> sysMembers = sysMemberMapper.selectSysMemberList(param);
                map.put("user", ObjectUtils.isNotEmpty(sysMembers)?sysMembers.get(0):null);
                return AjaxResult.success(map);
            }
            return AjaxResult.success(res);
        }
        return AjaxResult.error("暂无数据");
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
